using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Net;

using EveApiLib;
using NotifyClient;

namespace EveSkillPocket
{
    public partial class fCharacter : Form
    {
        private EVESettings eSettings = new EVESettings();
        private EveApiLogic eaLogic;
        private NotifyIcon notifyIcon;
        private bool startup;
        private bool error = false;

        public fCharacter()
        {
            this.startup = true;
            if (!this.eSettings.loadConfiguration())
            {
                this.eSettings.saveConfiguration();
            }
            this.InitializeComponent();
            this.eaLogic = new EveApiLogic(this, this.eSettings);
            this.doSetupWarningCMB(this.cmbSettingsWarning);
            this.doSetupUpdateCMB(this.cmbSettingsUpdate);

            doCancelSettings();
            this.startup = false;

        }

        private void fCharacter_Load(object sender, EventArgs e)
        {
            lblError.Text = "";
            if (this.eSettings.Config == null)
            {
                this.error = true;
                MessageBox.Show("Eve Skill Pocket was unable to load your character.xml file. Please make sure you have a correct (minimal) character.xml file in your EveSkillMobile directory.", "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                base.Close();
            }
            else if (this.eSettings.NotifyIcon)
            {
                this.notifyIcon = new NotifyIcon();
                this.notifyIcon.Click += new EventHandler(this.notifyIcon_Click);
                this.AddIcon();
            }

            this.do_update();
        }

        private void fCharacter_Activated(object sender, EventArgs e)
        {
            if (!this.error)
            {
                this.lblCharacterName.Text = this.eSettings.Config.ActivatedChar.Name.ToString();
                this.lblCharacterCorp.Text = this.eSettings.Config.ActivatedChar.CorpName.ToString();
            }
        }

        private void AddIcon()
        {
            IntPtr hIcon = Win32.LoadIcon(Win32.GetModuleHandle(null), "#32512");
            this.notifyIcon.Add(hIcon);
        }

        private void notifyIcon_Click(object sender, EventArgs e)
        {
            base.Activate();
        }

        private void miUpdate_Click(object sender, EventArgs e)
        {
            this.do_update();
        }

        private void do_update()
        {
            this.lblError.Text = "";
            this.eaLogic.DoUpdate();
            //string picUri = "http://img.eve.is/serv.asp?s=256&c=" + this.eSettings.Config.CharacterID.ToString();
        }

        private void ShowCharacters(object sender, EventArgs e)
        {
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            new fAccount(this.eSettings.Config).ShowDialog();
        }

        public static string GetDir()
        {
            string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            if (directoryName.LastIndexOf(Path.DirectorySeparatorChar) != (directoryName.Length - 1))
            {
                directoryName = directoryName + Path.DirectorySeparatorChar;
            }
            return directoryName;
        }

        private void cbSettingsAutoUpdate_CheckStateChanged(object sender, EventArgs e)
        {
            if (this.cbxSettingsAutoUpdate.Checked)
            {
                this.eaLogic.AutoUpdate = true;
            }
            else
            {
                this.eaLogic.AutoUpdate = false;
            }
        }

        private void miMenuExit_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void cbxSettingsNotify_CheckStateChanged(object sender, EventArgs e)
        {
            if (this.startup == false)
                MessageBox.Show("You have to restart EveSkillPocket for this setting to take effect.", "Info");
        }

        #region Settings Panel

        private void doSelectValue(ComboBox box, int value)
        {
            for (int i = 0; i < box.Items.Count; i++)
            {
                SettingItem item = (SettingItem)box.Items[i];
                if (item.Value == value)
                {
                    box.SelectedIndex = i;
                    return;
                }
            }
        }

        private void doSetupUpdateCMB(ComboBox box)
        {
            box.Items.Add(new SettingItem(1, "Every Hour"));
            box.Items.Add(new SettingItem(2, "2 hours"));
            box.Items.Add(new SettingItem(3, "3 hours"));
            box.Items.Add(new SettingItem(4, "4 hours"));
        }
        
        private void doSetupWarningCMB(ComboBox box)
        {
            box.Items.Add(new SettingItem(0, "On Completion"));
            box.Items.Add(new SettingItem(5, "5min to comp."));
            box.Items.Add(new SettingItem(10, "10min to comp."));
            box.Items.Add(new SettingItem(15, "15min to comp."));
        }

        private void doSetupTodayCBX()
        {
            string strDLLPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\EveSkillPocketToday.dll";
            if ((!File.Exists(strDLLPath)) || !TodayPluginRegistry.IsInstalled("EveSkillPocket"))
            {
                this.cbxSettingsToday.Checked = false;
                this.cbxSettingsToday.Enabled = false;
            }
            else
            {
                this.cbxSettingsToday.Enabled = true;
                this.cbxSettingsToday.Checked = this.eSettings.Today;
            }
        }

        private void cbxSettingsToday_CheckStateChanged(object sender, EventArgs e)
        {
            if (this.cbxSettingsToday.Checked)
            {
                string dll = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\EveSkillPocketToday.dll";
                TodayPluginRegistry.Install("EveSkillPocket", dll, true, 0L, false, 2L);
            }
            else
            {
                TodayPluginRegistry.Uninstall("EveSkillPocket");
            }
        }

        public int ConfigUpdateInterval
        {
            get
            {
                SettingItem selectedItem = (SettingItem)this.cmbSettingsUpdate.SelectedItem;
                if (selectedItem == null)
                {
                    return -1;
                }
                return selectedItem.Value;
            }
        }

        public int ConfigWarn
        {
            get
            {
                SettingItem selectedItem = (SettingItem)this.cmbSettingsWarning.SelectedItem;
                if (selectedItem == null)
                {
                    return -1;
                }
                return selectedItem.Value;
            }
        }

        public bool NotifyIcon
        {
            get
            {
                return this.cbxSettingsNotify.Checked;
            }
        }

        private void doSaveSettings()
        {
            int iConfigWarn = this.ConfigWarn;

            if (iConfigWarn > 0)
                this.eSettings.Warning = iConfigWarn;

            int iConfigUpdateInterval = this.ConfigUpdateInterval;
            if (iConfigUpdateInterval > 0)
            {
                this.eSettings.AutoUpdateInterval = iConfigUpdateInterval;
            }
            this.eSettings.NotifyIcon = this.cbxSettingsNotify.Checked;
            this.eSettings.Today = this.cbxSettingsToday.Checked;
            this.eSettings.AutoUpdate = this.cbxSettingsAutoUpdate.Checked;
            this.eSettings.saveConfiguration();
            this.cbxSettingsAutoUpdate.Text = "Update every " + this.eSettings.AutoUpdateInterval + " hour";
            if (this.cbxSettingsAutoUpdate.Checked)
                this.eaLogic.DoUpdate();
        }

        private void doCancelSettings()
        {
            this.doSelectValue(this.cmbSettingsWarning, eSettings.Warning);
            this.doSelectValue(this.cmbSettingsUpdate, eSettings.AutoUpdateInterval);

            doSetupTodayCBX();
            this.cbxSettingsNotify.Checked = this.eSettings.NotifyIcon;
            this.cbxSettingsAutoUpdate.Checked = this.eSettings.AutoUpdate;
        }

        private void btnSettingsSave_Click(object sender, EventArgs e)
        {
            doSaveSettings();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            doCancelSettings();
        }
        #endregion
        
        private void doUpdateWallet()
        {
            if ((this.eSettings.Config.ActivatedAccount != null) || (this.eSettings.Config.ActivatedChar != null))
            {
                EveWallet char_wallet = new EveWallet(EveWalletType.WALLET_CHARACTER);
                EveWallet corp_wallet = new EveWallet(EveWalletType.WALLET_CORP);

                if (!char_wallet.Load(this.eSettings.Config))
                {
                    if (char_wallet.ErrorCode == 200)
                    {
                        this.lblError.Text = "Unable to retrieve wallet. You need to use the full access API Key to use this feature.";
                    }
                    else
                    {
                        this.lblError.Text = "Unable to retrieve personal wallet.\nEve API Error: " + char_wallet.Error;
                    }
                }
                else
                {
                    this.lblCharacterBalance.Text = char_wallet.GetTotalBalance().ToString("#,0.00");
                }
                if (!corp_wallet.Load(this.eSettings.Config))
                {
                    if (corp_wallet.ErrorCode == 200)
                    {
                        this.lblError.Text = "Unable to retrieve wallet. You need to use the full access API Key to use this feature.";
                    }
                    else
                    {
                        this.lblError.Text = "Unable to retrieve corporation wallets.\nEve API Error: " + corp_wallet.Error;
                    }
                }
                else
                {
                    foreach (EveWalletAccount account in corp_wallet.Accounts)
                    {
                        
                        //ListViewItem item2 = new ListViewItem();
                        //item2.Text = "" + account.AccountKey;
                        //item2.SubItems.Add(account.Balance.ToString("#,0.00"));
                        //this.wallet.Items.Add(item2);
                    }
                }
            }
        }
    }
}